import Taro, {
    navigateTo as _navigateTo,
    redirectTo as _redirectTo,
    switchTab as _switchTab,
    navigateBack as _navigateBack,
    reLaunch as _reLaunch,
    useRouter
} from "@tarojs/taro";
// import TokenUtils from "@/utils/token";

function switchTab(url: string, params?: {}, option?: Taro.switchTab.Option) {
    const newUrl = createUrl(url);
    return _switchTab({
        url: newUrl,
        ...option
    });
}

function reLaunch(url: string, params?: {}, option?: Taro.reLaunch.Option) {
    const newUrl = createUrl(url, params);
    return _reLaunch({
        url: newUrl,
        ...option
    });
}

//创建url
function createUrl(url: string, params?: {}): string {
    if (params) {
        const finalUrl = `${url}?` + (Object.entries(params).map(([key, value]) => `${key}=${value ? encodeURIComponent(String(value)) : ''}`).join('&'))
        // console.log('跳转的链接', finalUrl)
        return finalUrl;
    }
    return url;
}

/**
 * @fn navigateTo 需要跳转的应用内非 tabBar 的页面的路径
 * @url 路由url
 * @params 路由参数
 */
function navigateTo(url: string, params?: {}, option?: Taro.navigateTo.Option) {
    const newUrl = createUrl(url, params);
    return _navigateTo({
        url: newUrl,
        ...option
    });
}

/**
 * @fn navigateTo 需要跳转的应用内非 tabBar 的页面的路径
 * @url 路由url
 * @params 路由参数
 */
function navigateBack(delta: number = 1, option?: Taro.navigateBack.Option) {
    return _navigateBack({
        delta,
        ...option
    });
}

function redirectTo(url: string, params?: {}, option?: Taro.redirectTo.Option) {
    const newUrl = createUrl(url, params);
    return _redirectTo({
        url: newUrl,
        ...option
    });
}

const RouterUtils = {
    createUrl,
    navigateTo,
    redirectTo,
    switchTab,
    navigateBack,
    reLaunch,
    useRouter,
    //获取路由参数
    getRouterParams() {
        return Taro.getCurrentInstance().router?.params || {} as any
    },
    getCurrentFullPath: (params?: any) => {
        const router = Taro.getCurrentInstance().router || {} as any;
        return createUrl(router.path, {
            ...router.params,
            ...params
        })
    },
    //去授权页面
    toAuthPage(url?:string,params?:Record<string, any>) {
        // if (TokenUtils.getToken()) {
        //     return this.toPage(url,params)
        // }
        return navigateTo('/pages/login/index', {
            redirectUrl: url?createUrl(url, params):Taro.getCurrentInstance().router?.path
        })
    },
    toIndexPage() {
        return switchTab('/pages/index/index')
    },
    toPage(...args) {
        return new Promise((resolve, reject) => {
            // @ts-ignore
            this.navigateTo(...args).catch(() => {
                // @ts-ignore
                this.switchTab(...args).catch(() => {
                    // @ts-ignore
                    this.redirectTo(...args).catch(reject)
                })
            })
        })
    },
    //跳转
    toUrl: (url?: string) => {
        if (!url) {
            return;
        }
        //小程序地址
        if (url && url.startsWith('/pages/')) {
            Taro.navigateTo({url}).catch(() => {
                Taro.switchTab({url}).catch(() => {
                })
            })
        }
        if (process.env.TARO_ENV == 'weapp') {
            //互联网地址
            if (url && url.startsWith('http')) {
                RouterUtils.navigateTo('/pages/webview/index', {
                    url
                })
            }
        } else {
            window.location.href = url
        }
    },
}

export default RouterUtils

